package com.fyd.service;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.creator.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.fyd.entity.DbConf;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Service
public class DynamicChangeService {

    @Resource
    private DefaultDataSourceCreator dataSourceCreator;
    @Resource
    private ApplicationContext applicationContext;


    public String addDatasource(DbConf dbConf){
        DataSourceProperty dataSourceProperties = new DataSourceProperty();
        dataSourceProperties.setPoolName(dbConf.getName());
        dataSourceProperties.setUsername(dbConf.getUser());
        dataSourceProperties.setPassword(dbConf.getPwd());
        dataSourceProperties.setUrl(dbConf.getDbStr());
        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperties);
        DynamicRoutingDataSource 地 = applicationContext.getBean(DynamicRoutingDataSource.class);
        地.addDataSource(dbConf.getName(), dataSource);
        return "ok";
    }
}
